#!/bin/bash
if [ $# != 1 ]; then
    echo "please input video file name as the parameter"
    echo "example: ./run xxx.avi"
    exit
fi

if [ -f $1 ]; then
    ffmpeg -i $1 2> media.info
    filename=${1%.*}
    height=`sed -n 's/.*Video.*x\([0-9]\+\).*/\1/p' media.info`
    height=`echo $height'p'`
    framerate=`sed -n 's/.* \(.*\) tbr.*/\1/p' media.info`
else
    echo "can not open '$1'"
    exit
fi

rm -rf left.yuv
rm -rf center.yuv
rm -rf right.yuv
 
mknod left.yuv p
mknod center.yuv p
mknod right.yuv p

if [ $height = "720p" ]; then
    widthOrig=1280
    heightOrig=720
    widthOut=404
    inputsize=720x404
    outputsize=720x404
elif [ "$height" = "1080p" ]; then
    widthOrig=1920
    heightOrig=1080
    widthOut=608
    inputsize=1080x608
    outputsize=1280x720
elif [ "$height" = "2160p" ]; then
    widthOrig=3840
    heightOrig=2160
    widthOut=1214
    inputsize=2160x1214
    outputsize=1920x1080
elif [ "$height" = "360p" ]; then
    widthOrig=640
    heightOrig=360
    widthOut=202
    inputsize=360x202
    outputsize=360x202
elif [ "$height" = "450p" ]; then
    widthOrig=800
    heightOrig=450
    widthOut=252
    inputsize=450x252
    outputsize=448x252
else
    echo "unsupported video format, we only support 1280x720, 1920x1080, 3840x2160 video input"
    exit
fi

ffmpeg  -i $1 -y -strict experimental -acodec aac audio.aac
ffmpeg  -i $1 -f rawvideo pipe: | ./convert stdin $widthOrig $heightOrig $widthOut left.yuv center.yuv right.yuv &

ffmpeg  -s $inputsize -i left.yuv -i audio.aac -strict experimental -qscale 6 -y -r $framerate -s $outputsize $filename'_a'.mp4 &
ffmpeg  -s $inputsize -i center.yuv -i audio.aac -strict experimental -qscale 6 -y -r $framerate -s $outputsize $filename'_b'.mp4 &
ffmpeg -s $inputsize -i right.yuv -i audio.aac -strict experimental -qscale 6 -y -r $framerate -s $outputsize $filename'_c'.mp4

rm -rf left.yuv
rm -rf center.yuv
rm -rf right.yuv

